from Task.models import Task, Job
from rest_framework import viewsets
from Task.serializer import TaskSerializer, JobSerializer
from rest_framework.decorators import detail_route, list_route
from rest_framework.response import Response
from django.db.models import Count
from itertools import groupby
from rest_framework import filters

class TaskViewSet(viewsets.ReadOnlyModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = Task.objects.select_related().all()
    serializer_class = TaskSerializer
    filter_fields = ('module', 'name')


class JobViewSet(viewsets.ReadOnlyModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = Job.objects.select_related().all()
    filter_backends = (filters.SearchFilter, filters.DjangoFilterBackend)
    serializer_class = JobSerializer
    filter_fields = ('date', )
    search_fields = ('$name', )

    
    @list_route(methods=['get'])
    def status(self, request):
        status_hash = dict(Job.STATUS_CHOICES)
        queryset = self.filter_queryset(self.queryset)
        datas = queryset.values_list('id', 'status')
        total = datas.count()
        datas = groupby(datas, lambda d:d[1])

        status_result = {}
        for status_code, data in datas:
            data = [d for d in data]
            status = status_hash[status_code]
            count = len(data)
            status_result[status] = {'count':count, 'ids': [d[0] for d in data]}
            if status == 'success':
                del status_result[status]['ids']
        result = {}
        result['result'] = status_result
        result['total'] = total
        result['status'] = status_result.get('success', {}).get('count', 0) == total
        return Response(result)
